$(document).ready(function() {
	calendar.init();
	$("#modalSchedule .init-hiddeable").hide();
	$('#modalSchedule a:last').tab('show');
	initBorrados();
	select2.init();
	$("#btn_delete_user").click(function() {
		var r=confirm("¿Esta seguro de que desea borrar a este usuario del sistema?");
		if (r==true) {
		  $.post("http://localhost/clinica/adminmain/eraseUser",{id:userId}, function(data) {
		  	oTableBorrados.fnReloadAjax('http://localhost/clinica/secretarymain/xhrGetListOfErasedPatientsDt');
		  });
		}
	});
	$("#new_user_form").submit(function() {
		$.get("http://localhost/clinica/secretarymain/alreadyExistPatient", $("#new_user_form").serialize(), function(data) {
			if (data.length > 0) {
			    $('#dni_input').tooltip('show');
				return false;
			} else {
				$.post("http://localhost/clinica/secretarymain/xhrInsertPatient", $("#new_user_form").serialize(), function() {
					select2.init();
					$("#new_user_form input").each(function(data) {
						$(this).val("");
					});
					$("#collapseTwo").collapse('hide');
					return true;
				});
			}
		}, 'json');
		return false;
	});
	$("#update_user_form").submit(function() {
		$.post("http://localhost/clinica/secretarymain/xhrUpdatePatient", $("#update_user_form").serialize(), function() {
			return false;
		});
		return false;
	});
	$('#dni_input').tooltip({
        trigger: 'manual',
        title: "Ya existe este documento"
        }).on({
            focus: function() {
                $(this).tooltip('hide');
            }
    });
});

//Datatables jack bauer
(function($) {

//Datatables jack
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
    if ( typeof sNewSource != 'undefined' && sNewSource != null )
    {
        oSettings.sAjaxSource = sNewSource;
    }
    this.oApi._fnProcessingDisplay( oSettings, true );
    var that = this;
    var iStart = oSettings._iDisplayStart;
     
    oSettings.fnServerData( oSettings.sAjaxSource, [], function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable( oSettings );
         
        /* Got the data - add it to the table */
        for ( var i=0 ; i<json.aaData.length ; i++ )
        {
            that.oApi._fnAddData( oSettings, json.aaData[i] );
        }
         
        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        that.fnDraw();
         
        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
        {
            oSettings._iDisplayStart = iStart;
            that.fnDraw( false );
        }
         
        that.oApi._fnProcessingDisplay( oSettings, false );
         
        /* Callback user function - for event handlers etc */
        if ( typeof fnCallback == 'function' && fnCallback != null )
        {
            fnCallback( oSettings );
        }
    }, oSettings );
},	

/*
 * Function: fnGetColumnData
 * Purpose:  Return an array of table values from a particular column.
 * Returns:  array string: 1d data array 
 * Inputs:   object:oSettings - dataTable settings object. This is always the last argument past to the function
 *           int:iColumn - the id of the column to extract the data from
 *           bool:bUnique - optional - if set to false duplicated values are not filtered out
 *           bool:bFiltered - optional - if set to false all the table data is used (not only the filtered)
 *           bool:bIgnoreEmpty - optional - if set to false empty values are not filtered from the result array
 * Author:   Benedikt Forchhammer <b.forchhammer /AT\ mind2.de>
 */
$.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
	// check that we have a column id
	if ( typeof iColumn == "undefined" ) return new Array();
	
	// by default we only wany unique data
	if ( typeof bUnique == "undefined" ) bUnique = true;
	
	// by default we do want to only look at filtered data
	if ( typeof bFiltered == "undefined" ) bFiltered = true;
	
	// by default we do not wany to include empty values
	if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
	
	// list of rows which we're going to loop through
	var aiRows;
	
	// use only filtered rows
	if (bFiltered == true) aiRows = oSettings.aiDisplay; 
	// use all rows
	else aiRows = oSettings.aiDisplayMaster; // all row numbers

	// set up data array	
	var asResultData = new Array();
	
	for (var i=0,c=aiRows.length; i<c; i++) {
		iRow = aiRows[i];
		var aData = this.fnGetData(iRow);
		var sValue = aData[iColumn];
		
		// ignore empty values?
		if (bIgnoreEmpty == true && sValue.length == 0) continue;

		// ignore unique values?
		else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
		
		// else push the value onto the result data array
		else asResultData.push(sValue);
	}
	
	return asResultData;
}}(jQuery));

function fnCreateSelect( aData )
{
	var r='<select><option value=""></option>', i, iLen=aData.length;
	for ( i=0 ; i<iLen ; i++ )
	{
		r += '<option value="'+aData[i]+'">'+aData[i]+'</option>';
	}
	return r+'</select>';
}

var oSelectBorrados;

var select2 = {
	init : function() {
		//Disponibles
		$.get('secretarymain/xhrGetListOfPatients', function(data) {
			function patientFormatter(data) {
				return ""+data.lastname+', '+data.name+'';
			}
			oSelect = $("#listapacientes").select2({
				placeholder : "Buscar paciente...",
				formatInputTooShort:function(sarasa,sarasa2) {
					return "Ingrese mas de 2 caracteres";
				},
				formatNoMatches:function(morite) {
					return "No hay resultados";
				},
				minimumInputLength : 2,
				data : { 
					results: data, 
					text: function(item) { 
						return item.lastname+" "+item.name+" "+item.email+" "+item.dni; 
					} 
				},
				formatResult : patientFormatter, // omitted for brevity, see the source of this page
				formatSelection : patientFormatter, // omitted for brevity, see the source of this page
				dropdownCssClass : "bigdrop", // apply css that makes the dropdown taller
				escapeMarkup : function(m) {
					return m;
				} // we do not want to escape markup since we are displaying html in results
			})
			oSelect.on("change", function(e) { 
				openSchedule(e.val);
			})
		}, 'json');
	}
};

var oTableSchedule;
var oTableScheduleCancelados;
var oTableScheduleConcretados;
var oTableScheduleVencidos;
var oTableBorrados;
var oSearchTable;
var userId;

function openSchedule(id) {
	$("#modalSchedule").show();
	$("#modalSchedule .init-hiddeable").show();
	$('#modalSchedule a:first').tab('show');
	userId = id;
	$.get("http://localhost/clinica/secretarymain/getPatientById",{id:id},function(data) {
		//Profile edition
		$("#id_edit").attr('value',data[0].id);
		$("#name_edit").attr('value',data[0].name);
		$("#lastname_edit").val(data[0].lastname);
		$("#dni_edit").attr('value',data[0].dni);
		$("#address_edit").attr('value',data[0].address);
		$("#tel_edit").attr('value',data[0].tel);
		$("#email_edit").attr('value',data[0].email);
		$("#name_edit").attr('value',data[0].name);
		$("#dnitype_edit").prop("selectedIndex",data[0].dni_type);
		//Datatable vencidos
		if (!(typeof oTableScheduleVencidos === 'undefined')) {
			oTableScheduleVencidos.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientUnconcretedDt?id='+id);
		} else {
			oTableScheduleVencidos = $("#lista_schedule_vencidos").dataTable({
				"bProcessing": true,
	       	 	"sAjaxSource": 'http://localhost/clinica/secretarymain/getAllScheduleForPatientUnconcretedDt?id='+id,
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 5 ],
	        	      "mData": "id",
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '<div class="btn-group pull-right">';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsCancel('+data+')" title="Cancelar"><i class="icon-exclamation-sign"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsPendant('+data+')" title="Pendiente"><i class="icon-share-alt"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsConcreted('+data+')" title="Concretar"><i class="icon-ok"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="eraseSchedule('+data+')" title="Borrar"><i class="icon-trash"></i></a>';
	                  	htmlAction += '</div>';
	                  	return htmlAction;
	        	      	}
	        	   },
	        	    {
	        	      "aTargets": [ 2 ],
	        	      "mData": "doctor",
	        	      "mRender": function ( data, type, row ) {
		                  	return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
		                  	// $.get("http://localhost/clinica/adminmain/isDoctorInLicense?id="+data[0].id, function(dat) {
		                  		// if (data.length > 0) {
			                  		// return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
			                  	// } else {
			                  		// return '<p class="text-error">El Dr. '+data[0].name+' '+data[0].lastname+' se encuentra bajo licencia.</p>';
			                  	// }
		                  	// },'json');
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 0 ],
	        	      "mData": "date",
	        	      "mRender": function ( data, type, row ) {
		                  	if (data == 0)
		                  		return "Domingo";
		                  	if (data == 1)
		                  		return "Lunes";
		                  	if (data == 2)
		                  		return "Martes";
		                  	if (data == 3)
		                  		return "Miercoles";
		                  	if (data == 4)
		                  		return "Jueves";
		                  	if (data == 5)
		                  		return "Viernes";
		                  	if (data == 6)
		                  		return "Sabado";
	        	      	}
	        	    },
	        	],
	            "aoColumns": [
	              { "mDataProp": "date" },
		      	  { "mDataProp": "time" },
		      	  { "mDataProp": "doctor" },
		      	  { "mDataProp": "speciality" },
		      	  { "mDataProp": "socialhealth" },
	              { "mDataProp": "id" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
		//Datatable papelera
		initBorrados();
		//Datatable cancelados
		if (!(typeof oTableScheduleCancelados === 'undefined')) {
			oTableScheduleCancelados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientCancelDt?id='+id);
		} else {
			oTableScheduleCancelados = $("#lista_schedule_cancelados").dataTable({
				"bProcessing": true,
	       	 	"sAjaxSource": 'http://localhost/clinica/secretarymain/getAllScheduleForPatientCancelDt?id='+id,
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 5 ],
	        	      "mData": "id",
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '<div class="btn-group pull-right">';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsPendant('+data+')" title="Restaurar"><i class="icon-share-alt"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="eraseSchedule('+data+')" title="Borrar"><i class="icon-trash"></i></a>';
	                  	htmlAction += '</div>';
	                  	return htmlAction;
	        	      	}
	        	   },
	        	    {
	        	      "aTargets": [ 2 ],
	        	      "mData": "doctor",
	        	      "mRender": function ( data, type, row ) {
		                  	return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
		                  	// $.get("http://localhost/clinica/adminmain/isDoctorInLicense?id="+data[0].id, function(dat) {
		                  		// if (data.length > 0) {
			                  		// return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
			                  	// } else {
			                  		// return '<p class="text-error">El Dr. '+data[0].name+' '+data[0].lastname+' se encuentra bajo licencia.</p>';
			                  	// }
		                  	// },'json');
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 0 ],
	        	      "mData": "date",
	        	      "mRender": function ( data, type, row ) {
		                  	if (data == 0)
		                  		return "Domingo";
		                  	if (data == 1)
		                  		return "Lunes";
		                  	if (data == 2)
		                  		return "Martes";
		                  	if (data == 3)
		                  		return "Miercoles";
		                  	if (data == 4)
		                  		return "Jueves";
		                  	if (data == 5)
		                  		return "Viernes";
		                  	if (data == 6)
		                  		return "Sabado";
	        	      	}
	        	    },
	        	],
	            "aoColumns": [
	              { "mDataProp": "date" },
		      	  { "mDataProp": "time" },
		      	  { "mDataProp": "doctor" },
		      	  { "mDataProp": "speciality" },
		      	  { "mDataProp": "socialhealth" },
	              { "mDataProp": "id" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
		//Datatable concretados
		if (!(typeof oTableScheduleConcretados === 'undefined')) {
			oTableScheduleConcretados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientConcretedDt?id='+id);
		} else {
			oTableScheduleConcretados = $("#lista_schedule_concretados").dataTable({
				"bProcessing": true,
	       	 	"sAjaxSource": 'http://localhost/clinica/secretarymain/getAllScheduleForPatientConcretedDt?id='+id,
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 5 ],
	        	      "mData": "id",
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '<div class="btn-group pull-right">';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsCancel('+data+')" title="Cancelar"><i class="icon-exclamation-sign"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsUnconcreted('+data+')" title="Ausente"><i class="icon-remove"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsPendant('+data+')" title="Pendiente"><i class="icon-share-alt"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="eraseSchedule('+data+')" title="Borrar"><i class="icon-trash"></i></a>';
	                  	htmlAction += '</div>';
	                  	return htmlAction;
	        	      	}
	        	   },
	        	    {
	        	      "aTargets": [ 2 ],
	        	      "mData": "doctor",
	        	      "mRender": function ( data, type, row ) {
		                  	return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
		                  	// $.get("http://localhost/clinica/adminmain/isDoctorInLicense?id="+data[0].id, function(dat) {
		                  		// if (data.length > 0) {
			                  		// return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
			                  	// } else {
			                  		// return '<p class="text-error">El Dr. '+data[0].name+' '+data[0].lastname+' se encuentra bajo licencia.</p>';
			                  	// }
		                  	// },'json');
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 0 ],
	        	      "mData": "date",
	        	      "mRender": function ( data, type, row ) {
		                  	if (data == 0)
		                  		return "Domingo";
		                  	if (data == 1)
		                  		return "Lunes";
		                  	if (data == 2)
		                  		return "Martes";
		                  	if (data == 3)
		                  		return "Miercoles";
		                  	if (data == 4)
		                  		return "Jueves";
		                  	if (data == 5)
		                  		return "Viernes";
		                  	if (data == 6)
		                  		return "Sabado";
	        	      	}
	        	    },
	        	],
	            "aoColumns": [
	              { "mDataProp": "date" },
		      	  { "mDataProp": "time" },
		      	  { "mDataProp": "doctor" },
		      	  { "mDataProp": "speciality" },
		      	  { "mDataProp": "socialhealth" },
	              { "mDataProp": "id" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
		//Datatable pendientes
		if (!(typeof oTableSchedule === 'undefined')) {
			oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+id);
		} else {
			oTableSchedule = $("#lista_schedule").dataTable({
				"bProcessing": true,
	       	 	"sAjaxSource": 'http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+id,
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 5 ],
	        	      "mData": "id",
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '<div class="btn-group pull-right">';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsCancel('+data+')" title="Cancelar"><i class="icon-exclamation-sign"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsUnconcreted('+data+')" title="Ausente"><i class="icon-remove"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="markAsConcreted('+data+')" title="Concretar"><i class="icon-ok"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="eraseSchedule('+data+')" title="Borrar"><i class="icon-trash"></i></a>';
	                  	htmlAction += '</div>';
	                  	return htmlAction;
	        	      	}
	        	   },
	        	    {
	        	      "aTargets": [ 2 ],
	        	      "mData": "doctor",
	        	      "mRender": function ( data, type, row ) {
		                  	return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
		                  	// $.get("http://localhost/clinica/adminmain/isDoctorInLicense?id="+data[0].id, function(dat) {
		                  		// if (data.length > 0) {
			                  		// return '<p class="text-success">'+data[0].name+' '+data[0].lastname+' </p>';
			                  	// } else {
			                  		// return '<p class="text-error">El Dr. '+data[0].name+' '+data[0].lastname+' se encuentra bajo licencia.</p>';
			                  	// }
		                  	// },'json');
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 0 ],
	        	      "mData": "date",
	        	      "mRender": function ( data, type, row ) {
		                  	if (data == 0)
		                  		return "Domingo";
		                  	if (data == 1)
		                  		return "Lunes";
		                  	if (data == 2)
		                  		return "Martes";
		                  	if (data == 3)
		                  		return "Miercoles";
		                  	if (data == 4)
		                  		return "Jueves";
		                  	if (data == 5)
		                  		return "Viernes";
		                  	if (data == 6)
		                  		return "Sabado";
	        	      	}
	        	    },
	        	],
	            "aoColumns": [
	              { "mDataProp": "date" },
		      	  { "mDataProp": "time" },
		      	  { "mDataProp": "doctor" },
		      	  { "mDataProp": "speciality" },
		      	  { "mDataProp": "socialhealth" },
	              { "mDataProp": "id" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
		if (!(typeof oSearchTable === 'undefined')) {
			oSearchTable.fnReloadAjax('http://localhost/clinica/secretarymain/getAllEnableDoctors');
		} else {
			oSearchTable = $("#lista_doctors_schedule").dataTable({
				"bProcessing": true,
	       	 	"sAjaxSource": 'http://localhost/clinica/secretarymain/getAllEnableDoctors',
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 4 ],
	        	      "mData": "id",
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '<div class="btn-group pull-right">';
	                  	htmlAction += '<a  class="btn btn-primary" style="font-size: 10px;"  onclick="makeSchedule('+data+')"><i class="icon-pencil"></i> Concretar turno</a>';
	                  	htmlAction += '</div>';
	                  	return htmlAction;
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 3 ],
	        	      "mData": "socialhealth",
	        	      "mRender": function ( data, type, row ) {
	                  	var htmlAction = '<select class="tiny-font" style="width: 132px;">';
	                  	for (var i = 0; i < data.length; i++) {
	                  		htmlAction += '<option>'+data[i].socialhealth+'</option>';
	                  	}
	                  	htmlAction += '</select>';
	                  	return htmlAction;
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 2 ],
	        	      "mData": "speciality",
	        	      "mRender": function ( data, type, row ) {
	                  	var htmlAction = '<select class="tiny-font" style="width: 132px;">';
	                  	for (var i = 0; i < data.length; i++) {
	                  		htmlAction += '<option>'+data[i].speciality+'</option>';
	                  	}
	                  	htmlAction += '</select>';
	                  	return htmlAction;
	        	      	}
	        	    },
		        	],
	            "aoColumns": [
	              { "mDataProp": "name" },
		      	  { "mDataProp": "lastname" },
		      	  { "mDataProp": "speciality" },
		      	  { "mDataProp": "socialhealth" },
	              { "mDataProp": "id" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
		$("tfoot input").keyup( function () {
			/* Filter on the column (the index) of this element the plus one is cuz
			 * the rows are moved 1 column to the right */
			oSearchTable.fnFilter( this.value, $("tfoot input").index(this)+1 );
		});
	},'json');
}

function initBorrados() {
	if (!(typeof oTableBorrados === 'undefined')) {
			oTableBorrados.fnReloadAjax('http://localhost/clinica/secretarymain/xhrGetListOfErasedPatientsDt');
		} else {
			oTableBorrados = $("#lista_pacientes_borrados").dataTable({
				"bProcessing": true,
	       	 	"sAjaxSource": 'http://localhost/clinica/secretarymain/xhrGetListOfErasedPatientsDt',
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 7 ],
	        	      "mData": "id",
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '<div class="btn-group pull-right">';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="removePatient('+data+')" title="Borrar"><i class="icon-remove"></i></a>';
	                  	htmlAction += '<a  class="btn btn-mini" onclick="restorePatient('+data+')" title="Restaurar"><i class="icon-share-alt"></i></a>';
	                  	htmlAction += '</div>';
	                  	return htmlAction;
	        	      	}
	        	   },
	        	   {
	        	      "aTargets": [ 3 ],
	        	      "mData": "doctor",
	        	      "mRender": function ( data, type, row ) {
		                  	htmlAction = "";
		                  	if (data == "0") {
		                  		htmlAction = "LC";
		                  	} else if (data == "1") {
		                  		htmlAction = "Pasaporte";
		                  	} else if (data == "2") {
		                  		htmlAction = "DNI";
		                  	}
		                  	return htmlAction;
			        	}
	        	   },
	        	],
	            "aoColumns": [
	              { "mDataProp": "name" },
		      	  { "mDataProp": "lastname" },
		      	  { "mDataProp": "dni" },
		      	  { "mDataProp": "dni_type" },
		      	  { "mDataProp": "tel" },
		      	  { "mDataProp": "address" },
		      	  { "mDataProp": "email" },
	              { "mDataProp": "id" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
}

function restorePatient(id) {
	$.post("http://localhost/clinica/adminmain/restoreUser",{id:id}, function(data) {
	  	oTableBorrados.fnReloadAjax('http://localhost/clinica/secretarymain/xhrGetListOfErasedPatientsDt');
	  	select2.init();
	});
}

function removePatient(id) {
	var r=confirm("¿Esta seguro de que desea borrar a este usuario PERMANENTEMENTE del sistema?");
	if (r==true) {
	 	var r=confirm("¿Tambien desea borrar los turnos de este usuario?");
		if (r==true) {
			$.post("http://localhost/clinica/adminmain/removeUserCascade",{id:id}, function(data) {
			  	oTableBorrados.fnReloadAjax('http://localhost/clinica/secretarymain/xhrGetListOfErasedPatientsDt');
			  	if (id == userId) {
			  		location.reload();
			  	}
			  });
		} else {
			$.post("http://localhost/clinica/adminmain/removeUser",{id:id}, function(data) {
			  	oTableBorrados.fnReloadAjax('http://localhost/clinica/secretarymain/xhrGetListOfErasedPatientsDt');
			  	if (id == userId) {
			  		location.reload();
			  	}
			  });
		}
	  
	}
	
}

function markAsCancel(id) {
	var r=confirm("¿Esta seguro de que desea actualizar el estado de este turno a \"Cancelado\"?");
	if (r==true) {
	  $.post("http://localhost/clinica/secretarymain/markAsCancel",{id:id}, function(data) {
	  	oTableScheduleCancelados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientCancelDt?id='+userId);
	  	oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
	  	oTableScheduleConcretados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientConcretedDt?id='+userId);
	  	oTableScheduleVencidos.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientUnconcretedDt?id='+userId);
	  	oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
	  });
	}
}

function markAsPendant(id) {
	var r=confirm("¿Esta seguro de que desea actualizar el estado de este turno a \"Pentiente\"?");
	if (r==true) {
	  $.post("http://localhost/clinica/secretarymain/markAsPendant",{id:id}, function(data) {
	  	oTableScheduleCancelados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientCancelDt?id='+id);
	  	oTableScheduleConcretados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientConcretedDt?id='+userId);
	  	oTableScheduleVencidos.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientUnconcretedDt?id='+userId);
	  	oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
	  });
	}
}

function markAsUnconcreted(id) {
	var r=confirm("¿Esta seguro de que desea actualizar el estado de este turno a \"Ausente\"?");
	if (r==true) {
	  $.post("http://localhost/clinica/secretarymain/markAsUnconcreted",{id:id}, function(data) {
	  	oTableScheduleCancelados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientCancelDt?id='+id);
	  	oTableScheduleConcretados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientConcretedDt?id='+userId);
	  	oTableScheduleVencidos.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientUnconcretedDt?id='+userId);
	  	oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
	  });
	}
}

function markAsConcreted(id) {
	var r=confirm("¿Esta seguro de que desea actualizar el estado de este turno a \"Concretado\"?");
	if (r==true) {
	  $.post("http://localhost/clinica/secretarymain/markAsConcreted",{id:id}, function(data) {
	  	oTableScheduleCancelados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientCancelDt?id='+id);
	  	oTableScheduleConcretados.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientConcretedDt?id='+userId);
	  	oTableScheduleVencidos.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientUnconcretedDt?id='+userId);
	  	oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
	  });
	}
}

function eraseSchedule(id) {
	var r=confirm("¿Esta seguro de que desea borrar a este turno del sistema?");
	if (r==true) {
	  $.post("http://localhost/clinica/adminmain/eraseSchedule",{id:id}, function(data) {
	  	oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
	  });
	}
}

var schedulesCal;

//Magic fella its magic
function addZ(n){return n<10? '0'+n:''+n;}

var fuckingShit = true;

function makeSchedule(id) {
	fuckingShit = true;
	if (typeof schedulesCal == "undefined") {
		createScheduleCalendar(id);
	} else {
		$("#calendar_schedules").fullCalendar('destroy');
		createScheduleCalendar(id);
	}
	$("#submit_newsched").click(function() {
		var eventId = $("#selected_schedule").val();
		var healthId = $("#socialhealth_schedule").val();
		if (eventId != "" && fuckingShit) {
			fuckingShit = false;
			$.post('http://localhost/clinica/secretarymain/checkSchedule', {eventId: eventId, userId: userId, healthId:healthId}, function(data) {
				$("#modalCheckSchedule").modal('hide');
				oTableSchedule.fnReloadAjax('http://localhost/clinica/secretarymain/getAllScheduleForPatientDt?id='+userId);
			});
		}
		$("#msg_holder_schedule").text("Primero tiene que elegir un horario.");
	});
	$('#modalCheckSchedule').on('shown', function () {
		$.get("http://localhost/clinica/adminmain/getAllSocialHealthById?id="+id, function(dat) {
			$("#selected_schedule").val("");
			$("#msg_holder_schedule").text("");
			$("#socialhealth_schedule").children().remove();
			for (var n = 0; n < dat.length; n++) {
				var htmlOption = "";
				htmlOption += "<option value=\""+dat[n].id+"\">"+dat[n].text+"</option>";
				$("#socialhealth_schedule").append(htmlOption);
			}
		}, 'json');
		$("#calendar_schedules").fullCalendar('render');
	});
	$("#modalCheckSchedule").modal('show');
}

function createScheduleCalendar(id) {
	schedulesCal = $("#calendar_schedules").fullCalendar({
				height: 300,
				allDaySlot: false,
				axisFormat: "HH:mm:ss",
				events: "http://localhost/clinica/adminmain/getDoctorSchedules?id="+id,
				eventDataTransform: function(data) {
					var start = new Date();
					if (start.getDay()-data.day > 0) {
						start.setHours(start.getHours()-(24*(start.getDay()-data.day )));
					} else {
						start.setHours(start.getHours()+(24*(data.day-start.getDay())));
					}
					var startHour = data.start.split(":")[0];
					var startMinute = data.start.split(":")[1];
					var startSecond = data.start.split(":")[2];
					start.setHours(startHour);
					start.setMinutes(startMinute);
					start.setSeconds(startSecond);
					
					var end = new Date();
					if (end.getDay()-data.day > 0) {
						end.setHours(end.getHours()-(24*(end.getDay()-data.day )));
					} else {
						end.setHours(end.getHours()+(24*(data.day-end.getDay())));
					}
					var endHour = data.end.split(":")[0];
					var endMinute = data.end.split(":")[1];
					var endSecond = data.end.split(":")[2];
					end.setHours(endHour);
					end.setMinutes(endMinute);
					end.setSeconds(endSecond);
					
					var result = {
						id: data.id,
						title: data.title,
						start: start.getFullYear()+"-"+addZ(start.getMonth()+1)+"-"+addZ(start.getDate())+" "+data.start,
						end: end.getFullYear()+"-"+addZ(end.getMonth()+1)+"-"+addZ(end.getDate())+" "+data.end,
						allDay: false,
						editable: false
					}
					return result;
				},
				columnFormat: {
				    month: 'ddd',    // Mon
				    week: 'ddd', // Mon 9/7
				    day: 'ddd'  // Monday 9/7
				},
				weekNumbers: false,
				buttonText: {
				    prev:     '&lsaquo;', // <
				    next:     '&rsaquo;', // >
				    prevYear: '&laquo;',  // <<
				    nextYear: '&raquo;',  // >>
				    today:    'hoy',
				    month:    'mes',
				    week:     'semana',
				    day:      'dia'
				},
				dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
				defaultView: 'agendaWeek',
				header: "",
				eventClick: function(calEvent, jsEvent, view) {
					$("#selected_schedule").val(calEvent.id);
			        $(".fc-event").css('border-color', '#3a87ad');
			        $(this).css('border-color', 'red');
			   }
			});
}

var calendar = {
	init : function() {
		$('#calendar').fullCalendar({
			events : [{
				title : 'Turno de Simon Olavarria con el Dr. Quiroga',
				start : '2013-04-20'
			}, {
				title : 'Turno de Ricardo Fuseneco con la Dra. Arriaga',
				start : '2013-04-22',
				end : '2013-04-23'
			}, {
				title : 'Turno de Jose Fernandez con el Dr. Lujan',
				start : '2013-04-10 12:30:00',
				allDay : false // will make the time show
			}]
		})
	}
};

/** ui stuff */
function updateThumbnail() {
	var file = $('#picture_file').get(0).files[0];
    
	var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            canvas.width = 100;
            canvas.height = 100;
            ctx.drawImage(img,0,0);
        }
        img.src = event.target.result;
        $("#picture_thumbnail").attr('src', event.target.result);
        $("#picture_blob").attr('value', event.target.result);
    }
    reader.readAsDataURL(file);
}

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = 100;
    canvas.height = 100;
    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
	ctx.drawImage(img,0,0);
    return canvas.toDataURL("image/png");
}
